package net.bingosoft.common.resource;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.WeakHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.bingosoft.common.util.FileHelper;
import net.bingosoft.common.util.JavascriptUtil;

/**
 * 2008-5-30 下午01:48:34
 * Author:yangdongyu(yangdy@bingosoft.net)
 * ReadMe:将指定的文件的内容输出到html页面
 * ChangeLog:
 */
public class ResourceManager {
	/**
	 * We cache the script output for speed
	 */
	private static final  Map<String, String> fileCache = new WeakHashMap<String, String>();
	
	private ResourceManager(){}
	/**
	 * 
	 * @param request
	 * @param response
	 * @param relativeClass
	 * @param fileName
	 * @throws IOException
	 */
	public static void WriteContent2HTML(HttpServletRequest request,HttpServletResponse response,Class relativeClass,String fileName) throws IOException{
		String mimeType = FileHelper.getFileMimeType(fileName);
		String output = null;
		synchronized (fileCache) {
			output = fileCache.get(fileName);
			if(output == null){
				output = FileHelper.readFileFromJar(fileName, relativeClass);
				fileCache.put(fileName, output);
			}
		}
		if (mimeType.equals("text/javascript")){
			output = JavascriptUtil.compress(output, JavascriptUtil.LEVEL_DEBUGGABLE);
		}
		response.setContentType(mimeType+";charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println(output);
	}
	

}
